package com.testing.Utlis;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class ScreenshotUtil {
    /**
     * 截图存储路径
     */
    private static final String SCREENSHOT_PATH = System.getProperty("user.dir") + File.separator + "target" + File.separator + "test-output" + File.separator + "screenshot";

    /**
     * 截图
     *
     */
    public static void capture(WebDriver driver) {
        // 截图目录
        File screenshotFile = new File(SCREENSHOT_PATH);
        // 若文件夹不存在就创建该文件夹
        if (!screenshotFile.exists() && !screenshotFile.isDirectory()) {
            screenshotFile.mkdirs();
        }
        // 截图格式
        String screenshotFormat = ReadPropertiesUtil.readProperties(ReadPropertiesUtil.FILEPATH, "output.screenshot.format");
        // 时间格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); //转换时间格式
        String time = dateFormat.format(Calendar.getInstance().getTime()); //获取当前时间
        try {
            // 截图操作
            File sourcefile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            // 截图存储

            FileUtils.copyFile(sourcefile, new File(SCREENSHOT_PATH + File.separator + time + screenshotFormat));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
